﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;

namespace Wordpress.Phone.Models
{
    public class MRssSource : ISource
    {

        public event EventHandler<EventArgs> LoadCompleted;

        public event EventHandler<EventArgs> SaveCompleted;

        protected WebClient client;
        
        protected List<Movie> _items;

        public MRssSource()
        {
            this.client = new WebClient();
            
            this._items = new List<Movie>();
        }

        public void Load()
        {
            this._items.Clear();
            
            this.client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(xmlClient_DownloadStringCompleted);
            this.client.DownloadStringAsync(this.buildUri(App.Settings.MediaRssUrl));
        }

        

        public void Save(IEnumerable<Movie> birthdays)
        {
            throw new NotImplementedException();
        }

        public IEnumerable<Movie> Items()
        {
            return this._items;
        }

        protected Uri buildUri(Uri url)
        {
            UriBuilder baseUri = new UriBuilder(url);
            Random rand = new Random();
			string queryToAppend = "token="+rand.Next();

			if (baseUri.Query != null && baseUri.Query.Length > 1)
				baseUri.Query = baseUri.Query.Substring(1) + "&" + queryToAppend; 
			else
				baseUri.Query = queryToAppend; 

            return baseUri.Uri;
        }

        void xmlClient_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            (sender as WebClient).DownloadStringCompleted -= new DownloadStringCompletedEventHandler(xmlClient_DownloadStringCompleted);
            
            XDocument doc = XDocument.Parse(e.Result);

            IEnumerable<Movie> movies = from m in doc.Element("rss").Element("channel").Elements("item")
                                        select MRssSource.FromMRss(m);

            foreach (Movie m in movies)
            {
                this._items.Add(m);
            }

            if (LoadCompleted != null)
            {
                this.LoadCompleted(this, new EventArgs());
            }
        }

        private static Movie FromMRss(XElement el) {
            XNamespace mrss = "http://search.yahoo.com/mrss/";
            Uri url = new Uri((string)el.Element(mrss+"content").Attribute("url"), UriKind.Absolute);
            Movie movie = Movie.detect(url);
            movie.Title = (string)el.Element("title");
            movie.Description = (string)el.Element("description");
            
            XElement media = el.Element(mrss+"content");

            movie.Source = url;
            if (media.Element(mrss+"thumbnail") != null) {
                movie.Thumbnail = new Thumbnail { Source = new Uri((string)media.Element(mrss+"thumbnail").Attribute("url"), UriKind.Absolute) };
            }
            return movie;
        }
    }
}
